package com.shop.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author 'banxia'
 * @version 1.0
 * @description TODO
 * @date 2023/2/21 14:13
 */
@Configuration
public class CodeGeneratorConfig {
    //例子
    /*
        //输出目录
        private String filePath = "E:\\shopping2\\shopping-code-generation\\src\\main\\java";
        //主键策略
        private IdType idType = IdType.AUTO;
        //数据库（本机哪个数据库）
        private String dbName = "shopping";
        //生成包路径:com.shop.shopping-user
        private String moduleName = "shopping-user";
        private String parent = "com.shop";
        //表名,若有多张用逗号连接
        private String tableNames = "user";
        //数据库username
        private String username = "root";
        private String password = "123456";
     */
    //输出目录
//    @Value("${filePath}")
    private String filePath;
    //数据库（本机哪个数据库）
    @Value("${dbName}")
    private String dbName;
    //生成包路径:com.shop.shopping-user
    @Value("${moduleName}")
    private String moduleName;
    @Value("${parent}")
    private String parent;
    //表名,若有多张用逗号连接
    @Value("${tableNames}")
    private String tableNames;
    //数据库username
    @Value("${db.username}")
    private String username;
    @Value("${db.password}")
    private String password;

    //主键策略
    private IdType idType = null;

    //执行代码生成
    public void codeGenerator(IdType idType) {
        if (Strings.isBlank(dbName) || Strings.isBlank(tableNames) || idType == null
                || Strings.isBlank(moduleName) || Strings.isBlank(parent)) {
            try {
                throw new Exception("参数不可为空");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //获取程序根路径
        String fileRoot = System.getProperty("user.dir");
        //拼接为filePath
        filePath=fileRoot+"\\src\\main\\java";
        this.idType=idType;
        generator();
    }


    private void generator() {

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(filePath); //输出目录

        gc.setAuthor("banxia"); //作者名
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖

        gc.setServiceName("%sService");    //去掉Service接口的首字母I
        gc.setIdType(idType); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        String url="jdbc:mysql://localhost:3306/" + dbName + "?serverTimezone=GMT%2B8";
        System.out.println("url = " + url);
//        dsc.setUrl("jdbc:mysql://localhost:3306/" + dbName + "?serverTimezone=GMT%2B8");
        dsc.setUrl(url);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(username);
        dsc.setPassword(password);
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();

        //生成包：com.banxia.eduservice
        pc.setModuleName(moduleName); //模块名
        pc.setParent(parent);

        //生成包：com.banxia.controller
        pc.setController("controller");
        pc.setEntity("po");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        //表设置
        String[] tables = tableNames.split(",");

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude(tables);//根据数据库哪张表生成，有多张表就加逗号继续填写

        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);

        // 6、执行
        mpg.execute();
    }
}
